package com.mall.security.api.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.mall.bean.model.User;
import com.mall.common.exceptions.ShopException;
import com.mall.common.responses.ServerResponseEntity;
import com.mall.dao.UserMapper;
import com.mall.security.common.bo.UserInfoBO;
import com.mall.security.common.dto.UserInfoDTO;
import com.mall.security.common.enusm.SysType;
import com.mall.security.common.manager.PasswordManager;
import com.mall.security.common.manager.TokenManager;
import com.mall.security.common.vo.TokenInfoVO;
import io.swagger.v3.oas.annotations.Operation;
import jakarta.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("user")
public class UserLoginController {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private PasswordManager passwordManager;
    @Autowired
    private TokenManager tokenManager;

    @RequestMapping("/login")
    @Operation(summary = "账号密码(用于前端登录)", description = "通过账号/手机号/用户名密码登录，还要携带用户的类型，也就是用户所在的系统")
    public ServerResponseEntity<TokenInfoVO> loginPassword(
            @Valid @RequestBody UserInfoDTO userInfoDTO){
        String userNameOrPhone = userInfoDTO.getUserName();
        User user =this.getUser(userNameOrPhone);
        String loginPassword = user.getLoginPassword();
        passwordManager.checkLoginTime(userInfoDTO.getUserName(),loginPassword,user.getLoginPassword());

        //写一个统一登陆的方法
        //写道redis里面
        //实现简单的Outha2 功能
        UserInfoBO userInfoBO = new UserInfoBO();
        userInfoBO.setUserId(user.getUserId());
        userInfoBO.setSysType(SysType.ORIGIN.getValue());
        userInfoBO.setStatus(user.getStatus()==1);
        userInfoBO.setNickName(user.getNickName());
        TokenInfoVO tokenInfoVO = tokenManager.storeTokenGetVO(userInfoBO);
        return ServerResponseEntity.success(tokenInfoVO);

    }
    //TODO 正则校验未完成
    private User getUser(String userNameOrPhone) {
        //查询手机号（）1.验证格式
        User user =null;
        //2.查询
        user = userMapper.selectOne(new LambdaQueryWrapper<User>().eq(User::getUserPhone, userNameOrPhone));
        if(user==null){
            //不是手机号
            user = userMapper.selectByName(userNameOrPhone);
        }
        if(user==null){
            throw new ShopException("账号错误");
        }
        return user;
    }

}
